package db

import (
	"encoding/json"
	"errors"
	"fmt"
	treeUtil "github.com/bing127/go_utils"
	"gorm.io/gorm"
	"hr/api/dto"
)

type Menu struct {
	AppModel
	ParentId uint   `json:"parent_id"`
	Name     string `gorm:"size:64" json:"name"`
	Tag      string `gorm:"size:64" json:"tag"`
	Icon     string `gorm:"size:64" json:"icon"`
	Sort     string `gorm:"size:64" json:"sort"`
	CreateBy string `gorm:"size:128" json:"createBy"` // 创建人
	UpdateBy string `gorm:"size:128" json:"updateBy"` // 更新人
	Remark   string `gorm:"size:255" json:"remark"`   //备注
	Type     string `gorm:"size:255;" json:"type"`      // 1是菜单、2是按钮
	Status   string `gorm:"size:255;" json:"status"`

	Role   []*Role `gorm:"many2many:role_menu;" json:"-"`
}

func (s *Menu) TableName() string {
	return "menu"
}

// GetMenu 根据条件查找
func GetMenu(p map[string]interface{}, extra ...interface{}) (Menu, error, string) {
	f := Menu{}
	queryDb := GetInstance().Where(p).First(&f)
	if len(extra) > 0 {
		queryDb = queryDb.Where(extra)
	}
	err := queryDb.Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return f, errors.New("查无记录"), "0"
		}
		return f, errors.New(err.Error()), "1"
	}
	return f, nil, "2"
}

func JudgeMenu(ids []string) bool {
	f := make([]Menu, 0)
	err := GetInstance().Where("id IN ?", ids).Find(&f).Error
	if err != nil {
		return false
	}
	if len(f) == len(ids) {
		return true
	} else {
		return false
	}
}


func GetAllMenu(name string) ([]map[string]interface{}, error) {
	m := make([]Menu, 0)
	dbs := GetInstance().Model(&Menu{}).Order("--sort asc")
	if name != "" {
		dbs = dbs.Where("name LIKE ?", "%"+name+"%")
	}
	err := dbs.Find(&m).Error
	if err != nil {
		return nil, err
	}

	config := treeUtil.TreeConfig{
		ID:       "id",
		PID:      "parent_id",
		Children: "children",
	}
	mMap := make([]map[string]interface{}, 0)
	if len(m) > 0 {
		marshal, _ := json.Marshal(m)
		_ = json.Unmarshal(marshal, &mMap)
		i := config.GenerateTree(mMap)
		return i, err
	} else {
		return mMap, nil
	}
}

func CreateMenu(p dto.MenuRequest, user string) (Menu, error) {
	d := Menu{
		ParentId: p.ParentId,
		Name:     p.Name,
		Tag:      p.Tag,
		Icon:     p.Icon,
		Sort:     p.Sort,
		CreateBy: user,
		Remark:   p.Remark,
		Type:     p.Type,
		Status:   p.Status,
	}
	if err := GetInstance().Create(&d).Error;err !=nil {
		return d,errors.New("创建失败")
	}
	return d,nil
}


func UpdateMenu(id uint,p dto.MenuRequest, userId string) (Menu,error) {
	f := Menu{
		AppModel: AppModel{
			ID:        id,
		},
	}
	err := GetInstance().Model(&f).Updates(Menu{
		ParentId: p.ParentId,
		Name:     p.Name,
		Tag:      p.Tag,
		Icon:     p.Icon,
		Sort:     p.Sort,
		UpdateBy: userId,
		Remark:   p.Remark,
		Type:     p.Type,
		Status:   p.Status,
	}).Scan(&f).Error
	if err != nil {
		return f,err
	}
	return f,nil
}

func DeleteMenu(id uint) (Menu,error) {
	f := Menu{}
	err := GetInstance().Exec(fmt.Sprintf("DELETE FROM role_menu WHERE menu_id = %d", id)).Error
	if err != nil {
		return Menu{}, err
	}
	err = GetInstance().Unscoped().Where("id = ?", id).Delete(&f).Error
	if err != nil {
		return f, err
	}
	return f, nil
}